<template>
    <el-drawer title="采购计划" :visible.sync="visible" direction="rtl" :show-close="false" class="cart-drawer">
        <div class="cart-content">
            <el-row class="cart-header">
                <el-col :span="12">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                </el-col>
                <el-col :span="12" style="text-align: right">
                    <el-button type="text" @click="handleFullScreen">全屏查看</el-button>
                </el-col>
            </el-row>
            <div class="cart-body">
                <div v-for="(item, index) in cartList" :key="item.id">
                    <el-row class="mb8 cart-title">
                        <el-col :span="2">
                            <el-checkbox :label="item.id" :indeterminate="selectHalf[index]" v-model="selectAll[index]" @change="val => handleSelectAllChange(val, index)"></el-checkbox>
                        </el-col>
                        <el-col :span="14">
                            <span style="position: relative; padding-right: 36px">
                                {{ item.supply_name }}
                                <sub style="font-size: 12px; color: #ffba00; position: absolute; right: 8px; top: -4px" v-if="item.is_1688 == 1">1688</sub>
                            </span>
                        </el-col>
                        <el-col :span="8">{{ item.warehouse }}</el-col>
                    </el-row>
                    <el-checkbox-group v-model="selectItem[index]" @change="val => handleSelectItemChange(val, index)" v-if="item.sku_info.length > 0">
                        <el-row class="cart-row" v-for="sku in item.sku_info" :key="sku.id">
                            <el-col :span="2">
                                <el-checkbox :label="sku.id"></el-checkbox>
                            </el-col>
                            <el-col :span="18">
                                <div class="flex">
                                    <div style="width: 60px">
                                        <ImageUploadImg v-model="sku.image_url" :readOnly="true" class="small-img"></ImageUploadImg>
                                    </div>
                                    <div>
                                        <el-link type="primary">{{ sku.seller_sku }}</el-link>
                                        <div>{{ sku.spu }}</div>
                                    </div>
                                </div>
                            </el-col>
                            <el-col :span="4" @mouseenter.native="mouseEnter(sku, index)" @mouseleave.native="mouseLeave(sku, index)">
                                <div class="flex align-center mb8">
                                    <div style="margin-right: 4px; color: #f40">{{ sku.purchase_price }}</div>
                                    <i class="el-icon-delete" :style="{ opacity: sku.edit ? 1 : 0, cursor: 'pointer' }" @click="deleteRow(sku, index)"></i>
                                </div>
                                <div class="flex align-center">
                                    <i
                                        class="el-icon-remove-outline"
                                        :style="{ opacity: sku.edit ? 1 : 0, cursor: sku.purchase_nums > 1 ? 'pointer' : 'not-allowed' }"
                                        @click="countChange(sku, index, 'reduce')"
                                    ></i>
                                    <div style="margin: 0 8px">{{ sku.purchase_nums }}</div>
                                    <i class="el-icon-circle-plus-outline" :style="{ opacity: sku.edit ? 1 : 0, cursor: 'pointer' }" @click="countChange(sku, index, 'add')"></i>
                                </div>
                            </el-col>
                        </el-row>
                    </el-checkbox-group>
                </div>
            </div>
            <div class="cart-footer">
                <el-button type="primary" size="large" @click="handleSubmit" style="width: 100%">生成采购单</el-button>
            </div>
            <div class="cart-close" @click="closeDrawer"><i class="el-icon-caret-right"></i></div>
        </div>
    </el-drawer>
</template>
<script>
import { carPlan, delPlan, editPlan } from '@/api/purchase'
export default {
    name: 'CartDrawer',
    props: {
        value: {
            type: Boolean,
            default: false,
        },
    },
    computed: {
        visible: {
            get() {
                return this.value
            },
            set(val) {
                this.$emit('input', val)
            },
        },
    },
    watch: {
        value(val) {
        if (!val) return;
        // 获取父组件的 tableData
        const parentTableData = this.$parent?.tableData || [];
        const skuInfo = parentTableData.flatMap(item => item.sku_info);
        if (skuInfo.length === 0) return;
        // 更新 cartList 中的 sku_info
        this.cartList = this.cartList.map(item => ({
            ...item,
            sku_info: item.sku_info.map(temp => {
                if (temp.purchase_nums === 0) {
                    const target = skuInfo.find(sku => sku.seller_sku === temp.seller_sku);
                    if (target) {
                        temp.purchase_nums = target.suggest_quantity;
                    }
                }
                return { ...temp };
            }),
        }));
    },
    },
    data() {
        return {
            cartList: [],
            selectAll: [],
            selectHalf: [],
            selectItem: [],
            isIndeterminate: false,
            checkAll: false,
            cartCount: 0,
        }
    },
    created() {
        this.getCarPlan()
    },
    methods: {
        closeDrawer() {
            this.visible = false
        },
        handleSubmit() {
            // 将 selectItem 二维数组转化为一维数组，然后去重
            let ids = []
            this.selectItem.forEach(item => {
                ids = ids.concat(item)
            })
            ids = Array.from(new Set(ids))
            if (ids.length == 0) {
                return this.$message.error('请选择要生成采购单的商品')
            }
            this.handleFullScreen(ids)
            this.$router.push({
                path: '/purchase/order/plan-detail',
                query: { ids },
            })
        },
        handleFullScreen(ids) {
            this.$router.push({
                path: '/purchase/order/plan',
                query: { ids },
            })
        },
        handleCheckAllChange(val) {
            this.isIndeterminate = false
            if (!val) {
                this.selectAll = this.cartList.map(item => false)
                this.selectItem = this.cartList.map(item => [])
            } else {
                this.selectAll = this.cartList.map(item => true)
                this.cartList.map((item, index) => {
                    this.selectItem[index] = item.sku_info.map(sku => sku.id)
                })
            }
            this.$forceUpdate()
        },
        handleSelectAllChange(val, index) {
            this.selectHalf[index] = false
            this.selectItem[index] = val ? this.cartList[index].sku_info.map(item => item.id) : []
            this.checkAll = this.selectAll.every(item => item)
            this.isIndeterminate = this.selectAll.some(item => item) && !this.checkAll
            this.$forceUpdate()
        },
        handleSelectItemChange(val, index) {
            this.selectHalf[index] = val.length > 0 && val.length < this.cartList[index].sku_info.length
            this.selectAll[index] = val.length === this.cartList[index].sku_info.length
            this.checkAll = this.selectAll.every(item => item)
            this.isIndeterminate = this.selectAll.some(item => item) && !this.checkAll
            this.$forceUpdate()
        },
        getCarPlan() {
            carPlan().then(res => {
                this.cartList = res.data.list.map(item => {
                    // 初始化 selectAll 和 selectItem this.selectHalf
                    this.selectAll.push(false) // 默认未全选
                    this.selectHalf.push(false) // 默认未半选
                    this.selectItem.push([]) // 默认未选择任何 SKU
                    item.sku_info = item.sku_info.map(sku => {
                        sku.edit = false
                        return sku
                    })
                    return item
                })
                this.cartCount = this.cartList.reduce((total, item) => total + item.sku_info.length, 0)
                this.$emit('getCartCount', this.cartCount)
            })
        },
        mouseEnter(row, $index) {
            const updatedSkuInfo = this.cartList[$index].sku_info.map(item => {
                if (item.id === row.id) {
                    return { ...item, edit: true }
                } else {
                    return { ...item, edit: false }
                }
            })
            // 替换原数组
            this.$set(this.cartList[$index], 'sku_info', updatedSkuInfo)
        },
        mouseLeave(row, $index) {
            const updatedSkuInfo = this.cartList[$index].sku_info.map(item => {
                return { ...item, edit: false }
            })
            // 替换原数组
            this.$set(this.cartList[$index], 'sku_info', updatedSkuInfo)
        },
        deleteRow(row) {
            this.$confirm('是否确认删除该数据?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    delPlan({ id: row.id }).then(res => {
                        this.$message.success('删除成功')
                        this.getCarPlan()
                    })
                })
                .catch(() => {})
        },
        countChange(row, $index, type) {
            let purchase_nums = row.purchase_nums
            if (type === 'add') {
                editPlan({ id: row.id, planNumber: ++purchase_nums }).then(res => {
                    // this.$message.success('修改成功')
                    this.getCarPlan()
                })
            } else {
                if (purchase_nums < 1) {
                    this.$message.error('采购数量不能小于1')
                    return
                }
                editPlan({ id: row.id, planNumber: --purchase_nums }).then(res => {
                    // this.$message.success('修改成功')
                    this.getCarPlan()
                })
            }
        },
    },
}
</script>
<style>
.cart-drawer .el-drawer,
.cart-drawer .el-drawer .el-drawer__body {
    overflow: visible;;
}
 
</style>
<style lang="scss" scoped>
.cart-content {
    height: calc(100vh - 73px);
    display: flex;
    flex-direction: column;
    align-items: stretch;
    position: relative;
}
.cart-close {
    cursor: pointer;
    position: absolute;
    width: 50px;
    height: 200px;
    left: -50px;
    top: 35%;
    z-index: 5000;
    border-radius:  5px 0 0 5px;
    line-height: 200px;
    text-align: center;
    background: #eee;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

::v-deep .cart-body {
    flex: 1;
    overflow-y: auto;
    .el-checkbox__label {
        width: 0;
        padding: 0;
        color: transparent;
    }
}
.cart-header {
    padding: 8px 12px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
}
.cart-title {
    font-size: 14px;
    padding: 8px 12px;
    background-color: #ddd;
}
.cart-row {
    font-size: 14px;
    padding: 8px 12px;
    border-bottom: 1px solid #f5f5f5;
}
.cart-footer {
    padding: 8px 12px;
    border-top: 1px solid #ddd;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
